package Thread;

public class LockTest {

    public static void main(String[] args) {
        ThreadSafeTest test = new ThreadSafeTest();
        Thread tA = new Thread(test); // 实例化4个线程
        Thread tB = new Thread(test);
        Thread tC = new Thread(test);
        Thread tD = new Thread(test);
        tA.start(); // 启动线程
        tB.start();
        tC.start();
        tD.start();
    }
}

class ThreadSafeTest implements Runnable {

    /************ 创建锁对象 ************/
    final Object lockObj = new Object();
    int num = 10;

    @Override
    public void run() {
        while (true) {
            // 同步 方法一
            // synchronized (lockObj) {
            // if (num > 0) {
            // try {
            // Thread.sleep(100);
            // } catch (Exception e) {
            // e.printStackTrace();
            // }
            // System.out.println("车票剩余：" + num-- + "张");
            // }
            // }
            doit();// 同步 方法二
        }
    }

    private synchronized void doit() { // 定义同步方法
        if (num > 0) {
            try {
                Thread.sleep(100);
            } catch (Exception e) {
                e.printStackTrace();
            }
            System.out.println("车票剩余：" + num-- + "张");
        }
    }

}
